<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Redpacket;
use think\Config;
use app\common\model\PrizeDraw;
use app\common\model\User as UserModel;
use fast\Random;
use org\login\Wxapp;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wxappLogin1','wxappLogin2'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $data = $this->auth->getUser();
        unset($data['password']);
        unset($data['salt']);
        unset($data['createtime']);
        unset($data['updatetime']);
        unset($data['status']);
        unset($data['loginip']);
        unset($data['loginfailure']);
        unset($data['joinip']);
        unset($data['jointime']);
        unset($data['birthday']);
        unset($data['bio']);
        unset($data['score']);

        //获取用户抽奖次数 中奖次数 增加会员过期时间判断是否为会员

        $prizeDrawModel = new PrizeDraw();
        $prizeDrawData = $prizeDrawModel
            ->field('id,is_win')
            ->where(['user_id'=>$data['id']])
            ->select();
        $data['drawtimes'] = count($prizeDrawData);  //参与抽奖次数
        $is_win = array_count_values(array_column($prizeDrawData,'is_win'));
        $wintimes = 0;
        if (isset($is_win[1])){
            $wintimes = $is_win[1];
        }
        $data['wintimes'] = $wintimes;

        //判断是否为会员vip用户
        $data['is_member'] = ($data['expiretime'] && $data['expiretime'] > time()) ? 1 : 0;
        //头像url 转绝对地址
        $data['avatar'] = getRealUrl($data['avatar']);
        $data['expiretime'] = $data['expiretime'] ? date('Y-m-d',$data['expiretime']) : '';
        //用户邀请分享code
        $userModel = new UserModel();
        $data['invitecode'] = $userModel->getShareCodeByUserId($data['id']);



        $this->success('', $data);
        //$this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error('Invalid parameters');
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            //头像url 转绝对地址 ambercc
            $data['userinfo']['avatar'] = getRealUrl($data['userinfo']['avatar']);

            $this->success('Logged in successful', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error('Invalid parameters');
        }
        if ($mobile && strlen($mobile) < 10
            // && !Validate::regex($mobile, "^1\d{10}$")
        ) {
            $this->error('Mobile is incorrect');
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error('Captcha is incorrect');
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error('Account is locked');
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('Logged in successful', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email','');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error('Invalid parameters');
        }
        if (strlen($username) < 4){
            $this->error('Username Cannot be less than 4');
        }
        if (strlen($password) < 6){
            $this->error('Password Cannot be less than 6');
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error('Email is incorrect');
        }
        if ($mobile && strlen($mobile) < 10
           // && !Validate::regex($mobile, "^1\d{10}$")
        ) {
            $this->error('Mobile is incorrect');
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error('Captcha is incorrect');
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('Sign up successful', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success('Logout successful');
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error('Username already exists');
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error('Invalid parameters');
        }
        if (!Validate::is($email, "email")) {
            $this->error('Email is incorrect');
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error('Email already exists');
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error('Captcha is incorrect');
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error('Invalid parameters');
        }
        if ($mobile && strlen($mobile) < 10
            // && !Validate::regex($mobile, "^1\d{10}$")
        ) {
            $this->error('Mobile is incorrect');
        }

        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error('Mobile already exists');
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error('Captcha is incorrect');
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error('Invalid parameters');
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success('Logged in successful', $data);
            }
        }
        $this->error('Operation failed', $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error('Invalid parameters');
        }
        if (strlen($newpassword) < 6){
            $this->error('Password Cannot be less than 6');
        }

        if ($type == 'mobile') {
            if ($mobile && strlen($mobile) < 10
                // && !Validate::regex($mobile, "^1\d{10}$")
            ) {
                $this->error('Mobile is incorrect');
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error('User not found');
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error('Captcha is incorrect');
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error('Email is incorrect');
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error('User not found');
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error('Captcha is incorrect');
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success('Reset password successful');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户登录 弹出 未领奖 未领红包等数据
     */
    public function popup(){
        $data = [];

        $user_id = $this->auth->id;
        //获取今日未领奖 begin
        $prizeDrawModel = new PrizeDraw();
        $map = [
            'user_id'   => $user_id,
            'is_opened' => 1,
            'is_win'    => 1,
            'status'    => 0,
            'order_sn'  => NULL,
        ];
        $prizeDrawList = $prizeDrawModel
            ->field('id,prize_id,goods_id,opentime')
            ->with(['goods'=>function($query){
                $query->withfield('id,name,price,image');
            }])
            ->where($map)
            ->select();

        //自动弃奖
        $auto_giveup_time = Config::get('site.auto_giveup_time');
        $giveUpTime = 0;
        if ($auto_giveup_time > 0){
            $giveUpTime = $auto_giveup_time * 60 * 60;
        }else{
            //不自动弃奖
        }

        foreach ($prizeDrawList as $k => $v){
            $prizeDrawList[$k]['goods']['image'] = getRealUrl($v['goods']['image']);
            $prizeDrawList[$k]['countdown'] = $v['opentime'] + $giveUpTime;
        }
        //获取今日未领奖 end

        //TODO 获取最后一个抽奖的开奖时间，今日用户是否获奖，给用户显示领取红包，生成uuid 并时效缓存，可以后台设置，过期
        //用户今日有抽奖，但没有中奖,在最后一个开奖结束 - 到一段时间内登录或在线， 则获得红包，

        //查询过期时间内，未领取的红包 begin
        $redPacketModel = new Redpacket();
        $redPacketWhere = [
            'category'          => 1, //未中奖红包
            'expiretime'    => ['>',time()], //红包未过期
        ];
        $redPacket = $redPacketModel
            ->field('id,type,uuid,amount,unit_amount,send_time,expiretime')
            ->withCount(['userRedpacket'=>function($query)use($user_id){
                $query->where([
                    'user_id' => $user_id,
                ]);
            }])
            ->where($redPacketWhere)
            //->fetchSql(true)
            ->select();

        $redPacketDate = [];
        if ($redPacket){
            foreach ($redPacket as $key => $value){
                //已经领取
                if ($value['user_redpacket_count']) {
                    continue;
                }
                //判断用户是否有该红包领取资格
                $where = [
                    'opentime'  => ['BETWEEN',[strtotime(date('Y-m-d',$value['send_time'])),$value['send_time']]],
                    'user_id'   => $user_id,
                    'is_opened'   => 1,
                ];
                //查询是否参与抽奖 是否赢过
                $is_win = false;
                $prizeDraw = $prizeDrawModel->field('id,user_id,is_win')->where($where)->select();
                if ($prizeDraw){
                    foreach ($prizeDraw as $k => $v){
                        if ($v['is_win']) {
                            $is_win = true;
                            break;
                        }
                    }

                    if (!$is_win){
                        $arr['id'] = $value['id'];
                        $arr['uuid'] = $value['uuid'];
                        $redPacketDate[] = $arr;
                    }
                }

            }
        }
        //查询过期时间内，未领取的红包 end

        $data = [
            'prizeDrawList' => $prizeDrawList,
            //TODO 红包
            //'redPacket'     => $redPacketDate,
            'redPacket'     => [
                [
                    'id'    => rand(1,50),
                    'user_id'   => $user_id,
                    'amount'    => number_format(mt_rand(1,20),2),
                    'redpacket_id' => get_sn(10),
                ]
            ],
        ];

        $this->success('i18n:62',$data);
    }

    /**
     * 微信小程序创建用户，不登陆，只是保存登录态
     * @return array
     */
    public function wxappLogin1()
    {
        $code = $this->request->request('code');
        if (!$code) {
            $this->error('i18n:198');
        }
        $wxapp = new Wxapp();
        $result = $wxapp->codeToInfo($code);

        if (!$result['status']){
            $this->error($result['msg']);
        }
        $data = [
            'open_id' => $result['data'],
        ];
        $this->success('i18n:62',$data);
    }


    /**
     * 微信小程序传过来了手机号码，那么取他的手机号码
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wxappLogin2()
    {
        $open_id = $this->request->request('open_id');
        $iv = $this->request->request('iv');
        $edata = $this->request->request('edata');

        //如果新用户不需要手机号码登陆，但是有推荐人的话，校验推荐人信息
        $invitecode = $this->request->request('invitecode');

        if (!$open_id) {
            $this->error('open_id！');
        }
        if (!$iv) {
            $this->error('iv！');
        }
        if (!$edata) {
            //加密的encryptedData数据，这是个加密的字符串
            $this->error('edata！');
        }

        if ($invitecode && $invitecode != '') {
            $userModel = new UserModel();
            //解析用户分享code
            $pid = $userModel->getUserIdByShareCode($invitecode);
            $pinfo = $userModel->where(['id' => $pid])->find();
            if ($pinfo) {
                $pid = $pinfo['id'];
            } else {
                $this->error('i18n:197');
            }
        } else {
            $pid = 0;
        }

        $wxapp = new Wxapp();

        $result = $wxapp->updateWxInfo($open_id, $edata, $iv, $pid);

        if ($result['status']) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            //头像url 转绝对地址 ambercc
            $data['userinfo']['avatar'] = getRealUrl($data['userinfo']['avatar']);

            $this->success('i18n:196',$data);
        } else {
            $this->error($result['msg']);
        }
    }

}
